import React from 'react'
import styles from "../../css/AddCuiji.module.css";
import { AddCuiji } from '../../const/imgs'
import ProgressView from '../../view/ProgressView'
var map, geolocation;
/**
 * 参数
 * @param immediately  定位组件是否加载就直接定位
 * @param visibility   定位组件是否显示
 * @param getLocation  方法
 * @param formattedAddress     已定位到位置信息
 */
class GetLocation extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  componentDidMount() {
    if (this.props.immediately) {
      this.getLocation()
    }
  }
  getLocation = () => {
    const that = this
    this.setState({
      loading: true
    })
    //加载地图，调用浏览器定位服务
    map = new window.AMap.Map(this.refs.map2, {
      resizeEnable: true,
      zoom: 8,
    });
    map.plugin('AMap.Geolocation', function () {
      geolocation = new window.AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new window.AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition: 'RB'
      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition();
      window.AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
      window.AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });
    //解析定位结果
    function onComplete(data) {
      console.log(data)
      let str = {}
      str.lng = data.position.lng
      str.lat = data.position.lat
      str.accuracy = data.accuracy
      str.isConverted = data.isConverted
      console.log(str)
      // that.setState(str)
      // 坐标转换地理信息 
      that.getLocationInfo(str)
    }
    //解析定位错误信息
    function onError(data) {
    }
  }

  // 坐标转换地理信息  
  getLocationInfo = ({ lng, lat }) => {
    const that = this
    window.AMap.service('AMap.Geocoder', function () {//回调函数
      var geocoder = new window.AMap.Geocoder({
        city: '' //城市，默认：“全国”
      });
      var lnglatXY = [lng, lat];//地图上所标点的坐标

      geocoder.getAddress(lnglatXY, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          //获得了有效的地址信息:  即，result.regeocode.formattedAddress
          that.setState({
            locationInfo: result.regeocode,
            loading: false
          })
          // this.setState({
          //   loading:frue
          // })
          that.props.getLocation({
            lat: lat,
            lng: lng,
            ...result.regeocode
          })
          console.log(result)
        } else {
          //获取地址失败
        }
      });
    })

  }
  render() {
    const { formattedAddress, visibility } = this.props
    const { loading } = this.state
    return (
      <div className={styles['cuiji_item_location']} style={{ height: "32px" }}>
        <img src={AddCuiji.DW} style={{ display: visibility ? 'block' : 'none' }} alt='' />
        <div onClick={this.getLocation} style={{ display: visibility ? 'block' : 'none' }}>
          {
            !formattedAddress && !loading &&
            <span>获取当前位置</span>
          }
          {!formattedAddress && loading &&
            <div style={{ height: "32px", display: 'flex', alignItems: 'center', overflow: 'hidden' }}>
              <ProgressView
                visibility={true}
                mode={ProgressView.MODE_SMALL}
                top='0'
                style={{
                  display: 'block',
                  justifyContent: "center",
                  position: 'relative',
                  width: 'auto'
                }}
              />
            </div>
          }
          {
            formattedAddress &&
            <span>{formattedAddress}</span>
          }
        </div>
        <div ref='map2'>
        </div>
      </div>
    )
  }
}
export default GetLocation